package TwoSeach;

import org.junit.Test;

import javax.xml.bind.annotation.XmlID;
import java.util.Arrays;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: TwoSeach
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-11-04  10:18
 * @Description: TODO
 * @Version: 1.0
 */
public class 在排序数组中查找元素的第一个和最后一个位置34 {


    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        int firstIndex = firstPosition(nums, target);
        if (firstIndex == -1) {
            return new int[]{-1, -1};
        }
        int lastIndex = lastPosition(nums, target);
        return new int[]{firstIndex, lastIndex};
    }

    private int lastPosition(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            // 当为偶数的时候的选择后面哪一个
            int mid = (left + right + 1) >>> 1;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] == target) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        if (nums[right] == target) {
            return right;
        }
        return -1;
    }

    private int firstPosition(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = (left + right) >> 1;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] == target) {
                right = mid;
            } else {
                right = mid - 1;
            }
        }
        if (nums[left] == target) {
            return left;
        }
        return -1;
    }

    @Test
    public void test() {
        int[] ints = searchRange(new int[]{7, 7, 7, 8, 8, 8, 10}, 8);
        System.out.println(Arrays.toString(ints));
    }
}
